#!/usr/bin/ruby

#USAGE:
#./ffmpeg_n900.rb FILENAME
#Oputput filename is set automatically to be - FILENAME.n900.mp4
#
#DESCRIPTION:
#A small script to encode video for Nokia N900 (Maemo) platform. 
#It uses ffmpeg to encode and does some calculations to determine the correct size/resolution of output to preserve the original aspect ratio.

#file = File.expand_path(ARGV.first)
file = ARGV.first

#This regular expression was originally written for grep which probably doesn't support non-greedy match hence "[^,]*," instead of ".*,".
output = `ffmpeg -i "#{file}" 2>&1 | sed -n -r 's/Stream .*: Video: [^,]*, [^,]*, ([0-9]+x[0-9]+).*/\\1/p'`

isize = output.strip.split('x').map { |i| i.to_f }
osize = [800, (800 / (isize[0] / isize[1])).to_i]

puts "Original size: #{isize[0].to_i}x#{isize[1].to_i} (#{'%.2f' % (isize[0] / isize[1]) })"
puts "New size: #{osize[0]}x#{osize[1]} (#{'%.2f' % (osize[0].to_f / osize[1].to_f) })"

#Can't get libfaac to work, at least easily.
command = "ffmpeg -i \"#{file}\" -vcodec libx264 -vpre hq -vpre ipod640 -b 800k -s #{osize[0]}x#{osize[1]} -acodec libmp3lame -ab 128k -ac 2 \"#{file}.n900.mp4\" "
puts "Executing: #{command}"

puts "ok?"
$stdin.gets

system command

## COMMENT SECTION

=begin
## /usr/share/ffmpeg/libx264-hq.ffpreset
coder=1
flags=+loop
cmp=+chroma
partitions=+parti8x8+parti4x4+partp8x8+partb8x8
me_method=umh
subq=8
me_range=16
g=250
keyint_min=25
sc_threshold=40
i_qfactor=0.71
b_strategy=2
qcomp=0.6
qmin=10
qmax=51
qdiff=4
bf=3
refs=4
directpred=3
trellis=1
flags2=+wpred+mixed_refs+dct8x8+fastpskip+mbtree
wpredp=2

## /usr/share/ffmpeg/libx264-ipod640.ffpreset
coder=0
bf=0
refs=1
flags2=-wpred-dct8x8+mbtree
level=30
maxrate=10000000
bufsize=10000000
wpredp=0
=end

